package xin.examinationSystem.servlet;

import com.alibaba.fastjson.JSON;
import xin.examinationSystem.account.Admin;
import xin.examinationSystem.account.Student;
import xin.examinationSystem.account.Teacher;
import xin.examinationSystem.account.testPaper.topic.*;
import xin.examinationSystem.dao.topic.ITestPaperMapper;
import xin.examinationSystem.utils.Tools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用于判断是否登录,没有登录就重定向到登录页面,没有完成
 */
@WebServlet("/judgeIfLogin")
public class judgeIfLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean logInStatus = false;
        Cookie[] cookies = request.getCookies();
        for (Cookie tCookie : cookies) {
            if (tCookie.getName().equals("accountMessageTeacher")) {
                HttpSession session = request.getSession();
                Teacher attribute = (Teacher) session.getAttribute(tCookie.getValue());
                if (attribute != null) {
                    logInStatus = true;
                }
            }
        }

        for (Cookie tCookie : cookies) {
            if (tCookie.getName().equals("accountMessageStudent")) {
                HttpSession session = request.getSession();
                Student attribute = (Student) session.getAttribute(tCookie.getValue());
                if (attribute != null) {
                    logInStatus = true;
                }
            }
        }

        for (Cookie tCookie : cookies) {
            if (tCookie.getName().equals("accountMessage")) {
                HttpSession session = request.getSession();
                Admin attribute = (Admin) session.getAttribute(tCookie.getValue());
                if (attribute != null) {
                    logInStatus = true;
                }
            }
        }

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //如果没有登录,重定向到登录页面
        if (logInStatus) {
            out.write("YES");
        }else{
            out.write("NO");
        }
        out.flush();
        out.close();
    }
}
